package me.keiwu.task.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import me.keiwu.pub.data.ConfigType;
import me.keiwu.pub.data.ResponseV2;
import me.keiwu.pub.data.config.ExploreConfigBean;
import me.keiwu.pub.data.enums.NoticeType;
import me.keiwu.pub.data.service.UserInfoBean;
import me.keiwu.pub.service.WXService;
import me.keiwu.pub.util.CacheUtil;
import me.keiwu.task.rpc.NoticeRpc;
import me.keiwu.task.rpc.UserRpc;
import me.keiwu.task.rpc.UserStatisticsRpc;
import me.keiwu.task.service.ExploreService;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import me.keiwu.task.util.ExceptionUtil;
import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by kei on 01/02/2018.
 */
@Service
@Transactional
public class ExploreServiceImpl implements ExploreService {

    private static final Logger logger = LoggerFactory.getLogger(ExploreServiceImpl.class);

	@Autowired
	private CacheUtil cacheUtil;
	@Autowired
	private UserRpc userRpc;
	@Autowired
	private UserStatisticsRpc userStatisticRpc;
	@Autowired
	private NoticeRpc noticeRpc;
	@Autowired
	private WXService wxServiceImpl;
	@Autowired
	private ExceptionUtil exceptionUtil;

    public ResponseV2 stealGold(Long userId, Long stealId) throws UnsupportedEncodingException {
        if (!cacheUtil.getRefreshUsers(userId).contains(stealId)) {
            logger.warn("not contain stealId userId={}, stealId={}", userId, stealId);
            return ResponseV2.fail("不能偷该用户");
        }

        if (!cacheUtil.checkCanSteal(userId, stealId)) {
            return ResponseV2.fail("今天已经偷取过对方的星币了，每天只能偷对方一次哦");
        }

        ExploreConfigBean config = cacheUtil.getConfig(ConfigType.EXPLORE_CONFIG, ExploreConfigBean.class);
        if (config == null) return ResponseV2.fail("缺少探索配置");

        int userGold = userRpc.getUserGold(userId);
        int targetGold = userRpc.getUserGold(stealId);
        if (userGold < config.getStealCost()) return ResponseV2.fail("星币不足");
        if (targetGold < config.getStealGetMax()) return ResponseV2.fail("对方暂时没有星币可偷，先去其他星球试试吧");

        int cost = config.getStealCost();
        int get = RandomUtils.nextInt(config.getStealGetMin(), config.getStealGetMax());
        logger.info("stealGold userId={}, stealId={}, cost={}, get={}", userId, stealId, cost, get);

		if (userRpc.changeGold(userId, -Math.abs(cost))) {
			// 记录被偷的人
			this.cacheUtil.recordStealUser(userId, stealId);
			userRpc.changeGold(userId, Math.abs(get));
			userRpc.changeGold(stealId, -Math.abs(get));
			JSONObject json = new JSONObject();
			json.put("cost", cost);
			json.put("get", get);
			// 统计偷金币次数
			userStatisticRpc.incrStealGoldCount(userId);
			noticeRpc.notice(NoticeType.STEAL_GOLD.getType(), userId, stealId, true, get + "");

			// 判断是否要通知被偷的对方
			// 注意，这里是stealId
			if (isTimeForTmpMsg() && cacheUtil.canTemplateMsgForSteal(stealId)) {

				// 将偷取到的金币数量存放到Map集合中
				Map<String, Object> map = new HashMap<String, Object>();
				String fromUser = userRpc.userInfo(userId);
				UserInfoBean fromUserBean = JSONObject.parseObject(fromUser, UserInfoBean.class);
				String toUser = userRpc.userInfoCache(stealId);
				String userFormStr = userRpc.getUserForm(stealId);
				if (userFormStr == null || fromUserBean == null || toUser == null){

					exceptionUtil.logError(this.getClass(),"steal templatemsg","empty userform/touser for " + stealId + " or empty fromuser for " + userId);
					return ResponseV2.ok(json);
				}
				Map<String, Object> formMap = JSON.parseObject(userFormStr, Map.class);
				String formId = (String)formMap.get("formId");
				Long form_db_id = ((Number)formMap.get("id")).longValue();
				StringBuilder sbPage = new StringBuilder("pages/explore/explore-user/explore-user?userId=");
				sbPage.append(fromUserBean.getId());
				sbPage.append("&gender=");
				sbPage.append(fromUserBean.getGender());
				sbPage.append("&wxAvatarUrl=");
				sbPage.append(fromUserBean.getWxAvatarUrl());
				sbPage.append("&nickName=");
				sbPage.append(fromUserBean.getNickName());
				sbPage.append("&gold=");
				sbPage.append(fromUserBean.getGold());
				sbPage.append("&totalStep30=");
				sbPage.append(fromUserBean.getTotalStep30());
				sbPage.append("&pageIndex=0");
				sbPage.append("&dataIndex=0");
				String page = sbPage.toString();

				map.put("formId", formId);
				map.put("templateMsgType",3);
				map.put("goldCount", get);
				// 调用发送模板 传参发送消息
				// 3 表示 GOLD_CHANGED 账户发生变动（星币被偷）
				exceptionUtil.logError(this.getClass(),"steal templatemsg", "stealGold-pages:"+page);
				ResponseV2 resp = wxServiceImpl.sendTemplateMsg(fromUser, toUser,page, map);
				if(resp.getCode() == HttpStatus.OK.value()){
					userRpc.deleteUsedForm(form_db_id);
					cacheUtil.recordTemplateMsgForSteal(stealId);
					exceptionUtil.logError(this.getClass(),"steal templatemsg",
							"from:"+fromUserBean.getId()+" to:"+stealId+" with fromId:"+formId);
				}else if (resp.getCode() == 1) {
					userRpc.deleteUsedForm(form_db_id);
				} else {
					exceptionUtil.logError(this.getClass(),"steal templatemsg",resp.getMsg());
				}
			}

			return ResponseV2.ok(json);
		}
		return ResponseV2.fail("您的星币不足");
	}

	private boolean isTimeForTmpMsg() {
		Calendar rightNow = Calendar.getInstance();
		int hour = rightNow.get(Calendar.HOUR_OF_DAY);
		return (hour > 8 && hour <23);
	}

}
